<?php
class TasksController extends AppController {

	var $name = 'Tasks';
	var $uses = array ('TypeItem','Task','TaskItem','User','Status','Sprint','SprintPlan');
	var $helpers = array('Html', 'Form','Paginator','Phone','Csv');
	var $paginate = array('limit' => 10);
	function beforeFilter() {
		//parent::beforeFilter();
		$this->layout = 'controlpanel';
	}
	
	function index() {
		$this->Task->recursive = 1;
		$status = $this->Status->find("list",array('fields' => array('id','name')));
		$tasks = $this->paginate('Task',array('projects_id' => $this->Session->read('selectedProject')));
		//debug($tasks);
		
		foreach ($tasks as &$task) {
			$taskItems = $task['TaskItem'];
			$value = 0;
			$unValue = 0;
			
			if (count($taskItems) > 0) {
				$task['numberOfItem'] = count($taskItems);
				foreach ($taskItems as $item) {
					$value += ($item['type_items_id'] == 1 || $item['type_items_id'] == 4)?$item['realHour']:0;
					$unValue += ($item['type_items_id'] == 2 || $item['type_items_id'] == 3)?$item['realHour']:0;
				}
			}
			
			$task['value'] = $value;
			$task['unValue'] = $unValue;
			$task['items'] = count($taskItems);
		}
		$this->set('tasks', $tasks);
		$this->set('status', $status);
	}
	
	function add() {
		if (!empty($this->data)) {
			$this->Task->create();
			$this->data['Task']['tasks_types_id'] = 2;
			$this->data['Task']['status_id'] = 1;
			
			$user = $this->Auth->user();
			
			$this->data['Task']['created_users_id'] = $user['User']['id'];
			$this->data['Task']['projects_id'] = $this->Session->read('selectedProject');
			
			if ($this->Task->save($this->data)) {
				
				$this->Session->setFlash(__('The Task has been saved', true));
				$taskId = $this->Task->getLastInsertId();
				$this->data['SprintPlan']['tasks_id'] = $taskId;
				
				$this->SprintPlan->create();
				$this->SprintPlan->save($this->data);
				
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The Subscriber could not be saved. Please, try again.', true));
			}
		}
		
		$relativePoints = $this->_generateRelativePoints();
		$sprints = $this->Sprint->find("list", array('fields' => array('id','name'),'order' => 'name DESC'));
		
		$this->set(compact('relativePoints'));
		$this->set(compact('sprints'));
	}
	
	function edit($id = null) {
		
		if (empty($id)) {
			$this->Session->setFlash(__('Invalid Task', true));
			//$this->redirect(array('action' => 'index'));
		}
		
		$relativePoints = $this->_generateRelativePoints();
		$this->set(compact('relativePoints'));
		
		$task = $this->Task->findById($id);
		$status = $this->Status->find("list",array('fields' => array('id','name')));
		$this->set(compact('status'));
		
		$users = $this->_getListUsers();
		$this->set(compact('users'));
		
		if (!empty($this->data)) {
			$this->Task->create();
			
			if ($this->Task->save($this->data)){
				if(empty($this->data['page'])) {
					$this->redirect(array('controller' => 'dashboards','action' => 'index'));
				} else {
					$this->redirect(array('action' => 'index','page:'.$this->data['page']));
				}
			} else {
				$this->Session->setFlash(__('The Task could not be edited. Please, try again.', true));
			}
		}
		if (!empty($this->params['named']['page'])) {
			$page = $this->params['named']['page'];
			$this->set('page',$page);
		} else {
			$this->set('page',null);
		}	
		$sprints = $this->Sprint->find("list",array('fields' => array('id','name'),'order' => 'name DESC'));
		$this->set(compact('sprints'));
		
		$this->data = $task;
	}
	
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for task', true));
			$this->redirect(array('action' => 'index'));
		} else {
			$this->TaskItem->deleteItemsByTaskId($id);
			$this->Task->delete($id);
			$this->Session->setFlash(__('Task deleted', true));
			$this->redirect(array('action' => 'index'));
		}
		
		$this->Session->setFlash(__('The task could not be deleted. Please, try again.', true));
		$this->redirect(array('action' => 'index'));
	}
	
	function addItem () {
		if (!empty($this->data)) {
			$this->TaskItem->create();
			$this->data['TaskItem']['tasks_id'] = $this->data['Task']['id'];
			
			if ($this->TaskItem->save($this->data)) {
				$this->redirect(array('controller' => 'tasks','action'=>'index'));
			}
		} else {
			$id = $this->params['named']['id'];
			$this->Task->recursive = -1;
			
			$task = $this->Task->findById($id);
			$this->set('selectedTask',$task);
			
			$itemTypes = $this->TypeItem->find("list",array('fields' => array('id','name'),'order'=>'name'));
			$this->set(compact('itemTypes'));
		}
	}
	
	function editItem ($id = null) {
		if (empty($id)) {
			$this->Session->setFlash(__('Invalid Task', true));
		}
		
		
		$item = $this->TaskItem->findById($id);
		$task = $this->Task->findById($item['TaskItem']['tasks_id']);
		
		//debug($item);
		
		$this->set('selectedTask',$task);
		
		$itemTypes = $this->TypeItem->find("list",array('fields' => array('id','name'),'order'=>'name'));
		$this->set(compact('itemTypes'));
		
		if (!empty($this->data)) {
			//debug($this->data);
			$this->TaskItem->create();
			
			if ($this->TaskItem->save($this->data)){
				$this->redirect(array('controller' => 'tasks','action' => 'viewDetail','id:'.$this->data['TaskItem']['tasks_id']));
			} else {
				$this->Session->setFlash(__('The Task could not be edited. Please, try again.', true));
			}
		}
		
		$this->data = $item;
	}
	
	function deleteItem($id = null) {
		
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for item', true));
			$this->redirect(array('action' => 'index'));
		} else {
			$item = $this->TaskItem->findById($id);
			if ($this->TaskItem->delete($id)) {
				$this->Session->setFlash(__('Task deleted', true));
				$this->TaskItem->commit();
				$this->redirect(array('action' => 'viewDetail','id:'.$item['TaskItem']['tasks_id']));
			}
			
			$this->Session->setFlash(__('The item could not be deleted. Please, try again.', true));
			$this->redirect(array('action' => 'viewDetail','id:'.$id));
		}
	}
	
	function viewDetail () {
		$id = $this->params['named']['id'];
		$this->Task->recursive = -1;
		
		$task = $this->Task->findById($id);
		$this->set('selectedTask',$task);
		
		$listItems = $this->TaskItem->find("all",array('conditions'=>array('tasks_id' => $task['Task']['id'])));
		
		//debug($listItems);
		
		$this->set(compact('listItems'));
	}

	function search () {
		$this->paginate = array(
        	'conditions' => array('Subscriber.firstName LIKE' => '%'.$this->data['Subscriber']['subscriberKeyword'].'%')
   		);
		
		$this->set('subscribers', $this->paginate());
		$this->render('index');
	}
	
	function exportCsv () {
		$this->Task->recursive = 1;
		$status = $this->Status->find("list",array('fields' => array('id','name')));
		$tasks = $this->Task->find('all',array('conditions'=>array('projects_id' => $this->Session->read('selectedProject'))));
		//debug($tasks);
		foreach ($tasks as &$task) {
			$taskItems = $task['TaskItem'];
			$value = 0;
			$unValue = 0;
			
			if (count($taskItems) > 0) {
				$task['numberOfItem'] = count($taskItems);
				foreach ($taskItems as $item) {
					$value += ($item['type_items_id'] == 1 || $item['type_items_id'] == 4)?$item['realHour']:0;
					$unValue += ($item['type_items_id'] == 2 || $item['type_items_id'] == 3)?$item['realHour']:0;
				}
			}
			
			$task['value'] = $value;
			$task['unValue'] = $unValue;
			$task['items'] = count($taskItems);
		}
		$csvData[] = array('Task Name','Status','Responsible','Relative Point','Estimated Hours','Real Hours','Items','Value','Un Value');
		foreach ($tasks as $task) {
			$csvData[] = array($task['Task']['taskName'],$status[$task['Task']['status_id']],$task['ResUser']['firstName'].' '.$task['ResUser']['lastName'],
			$task['Task']['relativePoint'],$task['Task']['estimatedHour'],$task['Task']['realHour'],$task['items'],$task['value'],$task['unValue']);
		}
		$this->layout = '';
		$this->set('lines', $csvData);
		$this->set('fileName', 'tasks.csv');
	}
	
	private function _generateRelativePoints() {
		$relativePoints = array();
		$relativePoints['1'] = 1;
		$relativePoints['3'] = 3;
		$relativePoints['5'] = 5;
		$relativePoints['8'] = 8;
		$relativePoints['13'] = 13;
		$relativePoints['20'] = 20;
		$relativePoints['40'] = 40;
		$relativePoints['100'] = 100;
		
		return $relativePoints;
	}
	
	private function _getListUsers() {
		$users = $this->User->find("all",array('fields' => array('id','firstName','lastName'),'order'=>'userName'));
		$listUser = array();
		
		foreach ($users as $user) {
			$listUser[$user['User']['id']] = $user['User']['firstName'].' '.$user['User']['lastName'];
		}
		
		return $listUser;
	}

}
?>